package com.ocom.websocket.websocket.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.utils.HttpRequest;
import com.ocom.common.utils.HttpUtils;
import com.ocom.common.vo.nacos.NacosServiceVO;
import com.ocom.common.vo.nacos.ServiceVo;
import com.ocom.websocket.websocket.WsShare;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;


@RefreshScope
@Service
public class WsShareImpl implements WsShare {


	@Value("${spring.cloud.nacos.discovery.server-addr}")
	String serverAddr;

	// http://localhost:8848/nacos/v1/ns/instance/list?serviceName=SEATA_GROUP@@human

//	@Value("${ws.urls}")
//	String urls;

	/**
	 * 注入消息处理器
	 */
	@Override
	public void send(String companyId, String msg) {

		String nacosUrl= "http://"+serverAddr+"/nacos/v1/ns/instance/list?serviceName=SEATA_GROUP@@websocket";

		String res=HttpRequest.sendGet(nacosUrl);
		Gson gson=new Gson();

		System.out.println(res);

		NacosServiceVO nacosServiceVO=gson.fromJson(res,NacosServiceVO.class);

		if(nacosServiceVO.getHosts().size()>0){
			for (ServiceVo serviceVo:nacosServiceVO.getHosts()){
				if(serviceVo.getHealthy()==false){
					continue;
				}
				try{
					JSONObject jsonObject=new JSONObject();
					jsonObject.put("companyId",companyId);
					jsonObject.put("message",msg);
					HttpUtils.doPostBodyData("http://"+serviceVo.getIp()+":"+serviceVo.getPort()+"/sendWs",jsonObject,"utf-8");
				}catch (Exception e){

				}
			}
		}
//
//		String[] urlList=urls.split(",");

	}
}
